package org.thanos.demo.service;

import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.thanos.demo.processor.impl.DemoTaskProcessor;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;

@Service("taskService")
public class TaskServiceImpl implements TaskService {

    private static final Set<TaskEntity> DATA = new CopyOnWriteArraySet<>();

    static {
        DATA.add(new TaskEntity(1, "demo", 2, DemoTaskProcessor.class.getName(), "hello world", true, null, 5000L, 5000L, LocalDateTime.now(), LocalDateTime.now()));
    }

    @Override
    public List<TaskEntity> allTasks() {
        return DATA.stream().toList();
    }

    @Override
    public List<TaskEntity> allEnableTasks() {
        return DATA.stream().filter(TaskEntity::getEnable).collect(Collectors.toList());
    }

    @Override
    public TaskEntity selectById(Integer id) {
        Assert.notNull(id, "id must not be null");
        return DATA.stream().filter(taskEntity -> taskEntity.getId().equals(id)).findAny().orElse(null);
    }

    @Override
    public TaskEntity selectByName(String name) {
        Assert.notNull(name, "name must not be null");
        return DATA.stream().filter(taskEntity -> taskEntity.getName().equals(name)).findAny().orElse(null);
    }

    @Override
    public void insertTask(TaskEntity task) {
        DATA.add(task);
    }

    @Override
    public void updateTask(TaskEntity task) {
        DATA.add(task);
    }

    @Override
    public void disableTask(Integer id) {
        Assert.notNull(id, "id must not be null");
        DATA.forEach(taskEntity -> {
            if (taskEntity.getId().equals(id)) {
                taskEntity.setEnable(false);
            }
        });
    }

    @Override
    public void enableTask(Integer id) {
        Assert.notNull(id, "id must not be null");
        DATA.forEach(taskEntity -> {
            if (taskEntity.getId().equals(id)) {
                taskEntity.setEnable(true);
            }
        });
    }

    @Override
    public void deleteTask(Integer id) {
        Assert.notNull(id, "id must not be null");
        DATA.stream().filter(taskEntity -> !taskEntity.getId().equals(id));
    }
}
